// src/components/PreventingTransitionsExample.js

// 导入 react 核心库，简化 Component 写法.
import React, { Component } from 'react';
import {
  BrowserRouter as Router,
  Route,
  Link,
  Prompt,
} from 'react-router-dom';

const Example = () => (
  <div>
    <ul>
      <li><Link to="/">Form</Link></li>
      <li><Link to="/one">One</Link></li>
      <li><Link to="/two">Two</Link></li>
    </ul>

    <Route path="/" exact component={Form} />
    <Route path="/one" render={() => <h3>One</h3>} />
    <Route path="/two" render={() => <h3>Two</h3>} />
  </div>
);

/** 表单类. */
class Form extends Component {

  /*
  constructor() {
    super();
    this.state = {
      isBlocking: false,
    }
  }
  */

  state = {
    // 是否封锁，默认为 不封锁.
    isBlocking: false,
  }

  /** form 提交事件 */
  handleSubmit = (event) => {
    // 阻止触发浏览器默认提交行为.
    event.preventDefault();
    event.target.reset();

    this.setState({
      //取消 封锁.
      isBlocking: false
    });
  }

  /** input 输入事件 */
  handleChange = event => {
    this.setState({
      // 有输入内容时 开启 封锁.
      isBlocking: event.target.value.length > 0
    });
  }

  render() {
    // 简化 state 属性写法.
    const { isBlocking } = this.state;
    // 输入提示.
    const InputPrompt = "输入任意内容来阻止跳转...";
    // 封锁提示，返回 true 则接触封锁.
    const PromptMessage = location => (`你确定要去 ${location.pathname} ？`);
    // 封锁状态提示.
    const blockingStateMessage = isBlocking ? 'Yes! (请点击链接或返回按钮检查)' : 'Nope';

    return (
      <form onSubmit={this.handleSubmit} >
        {/* 提示组件，会调用默认的提示(Cancel/Yes) */}
        {/* when 设置默认是否触发提示 */}
        <Prompt when={isBlocking} message={PromptMessage} />

        {/* 封锁状态 */}
        <p>
          封锁状态： {blockingStateMessage}
        </p>
        <p>
          <input size="50" placeholder={InputPrompt} onChange={this.handleChange} />
        </p>
        <p>
          <button>提交停止封锁</button>
        </p>
      </form>
    )
  }
}

export default Example;
